package com.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.entity.Dept;

public class DeptDaoImpl extends BaseDao implements DeptDao {

	private Connection conn;
	private PreparedStatement stmt;
	private ResultSet rs;
	@Override
	public Serializable saveDept(Dept dept) {
		String sql="insert into dept(dname,loc)values(?,?)";
		Object[] args = {dept.getDname(),dept.getLoc()};
		int result = super.executeUpdate(sql, args);
		return result;
	}

	@Override
	public int deleteDept(int deptNo) {
		String sql = "delete from dept where deptno=?";
		Object [] args = {deptNo};
		int result  =super.executeUpdate(sql, args);
		return result;
	}

	@Override
	public int deleteDept(Dept dept) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int deteteDept(int[] deptno) {
		String deptnos = Arrays.toString(deptno);
		deptnos = deptnos.substring(1, deptnos.length()-1);
		String sql = "delete from dept where deptno in("+deptnos+")";
		int result = super.executeUpdate(sql, null);
		return result;
	}

	@Override
	public int updateDept(Dept dept) {
		String sql="update dept set dname=?,loc=? where deptNo=?";
		Object [] args = {dept.getDname(),dept.getLoc(),dept.getDeptNo()};
		int result = super.executeUpdate(sql, args);
		return result;
	}

	@Override
	public Dept findById(int deptNo) {
		Dept dept = null;
		try {
			String sql="select * from dept where deptno=?";
			conn  = BaseDao.getConnectionWeb();
			stmt = conn.prepareStatement(sql);
			stmt.setInt(1, deptNo);
			rs = stmt.executeQuery();
			while(rs.next()){
				dept = new Dept();
				dept.setDeptNo(rs.getInt("deptno"));
				dept.setDname(rs.getString("dname"));
				dept.setLoc(rs.getString("loc"));
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			BaseDao.closeAll(conn, stmt, rs);
		}
		return dept;
	}

	@Override
	public List<Dept> findByObject(Dept dept) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Dept> findAll() {
		 List<Dept> list = new ArrayList<>();
		String sql="select * from dept";
		conn  = BaseDao.getConnectionWeb();
		try {
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while(rs.next()){
				Dept dept = new Dept();
				dept.setDeptNo(rs.getInt("deptno"));
				dept.setDname(rs.getString("dname"));
				dept.setLoc(rs.getString("loc"));
				list.add(dept);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			BaseDao.closeAll(conn, stmt, rs);
		}
		return list;
	}
	public static void main(String[] args) {
		System.out.println(new DeptDaoImpl().findAll());
	}

}
